package pers.mtx.chatdemo.activity;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import pers.mtx.chatdemo.R;
import pers.mtx.chatdemo.service.WebSocketService;
import pers.mtx.chatdemo.util.chat.model.put.LongConnectionLoginDTO;

public class ChatActivity extends Activity {

    private Button logBtn;
    private Button chatBtn;
    WebSocketService wsService;



    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder iBinder) {
            WebSocketService.WebSocketBinder binder = (WebSocketService.WebSocketBinder) iBinder;
            wsService = binder.getService();
            Log.d("ChatActivity", "onServiceConnected");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d("ChatActivity", "onServiceDisconnected");
        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        Intent wsSocketService = new Intent(ChatActivity.this, WebSocketService.class);
        bindService(wsSocketService,mServiceConnection,BIND_AUTO_CREATE);

        setContentView(R.layout.chat);
        logBtn = findViewById(R.id.LogBtn);
        chatBtn = findViewById(R.id.chatBtn);




        logBtn.setOnClickListener(view -> {
            View inflate = this.getLayoutInflater().inflate(R.layout.login_dialog, null);
            AlertDialog dialog = new AlertDialog.Builder(this).create();
            dialog.setView(inflate);
            dialog.create();
            dialog.show();

            Button loginBtn = inflate.findViewById(R.id.login_log);
            EditText idText = inflate.findViewById(R.id.login_id);
            loginBtn.setOnClickListener(view1 -> {
                wsService.sendMessage(new LongConnectionLoginDTO(idText.getText().toString()));
            });

        });

        chatBtn.setOnClickListener(view -> {
            Intent intent = new Intent(ChatActivity.this, SendActivity.class);
            startActivity(intent);
        });
    }
}
